package com.xiaoman.httpremote.base;

import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.List;

public class EnvContextHolder {
    public static final String activePlaceholder = "{active}";
    public static final String envTemplate = "https://api-"+ activePlaceholder +".up3dlink.com";
    public static final List<String> effectiveActivePlaceholders = Arrays.asList("dev", "test", "pre", "pro", "en");
    public static final String classpathProperty = "config.chairSaas.ipAddr";
    private final String env;
    private static EnvContextHolder instance;

    private EnvContextHolder(String env) {
       this.env = env;
    }

    public static EnvContextHolder getInstance() {
        return getInstance("");
    }

    public static EnvContextHolder getInstance(String env) {
        if (instance == null || StringUtils.isBlank(instance.env)) {
            synchronized (EnvContextHolder.class) {
                if (instance == null || StringUtils.isBlank(instance.env)) {
                    if (env.endsWith("/") || env.endsWith("\\"))
                        env = env.substring(0, env.length() - 1);
                    instance = new EnvContextHolder(env);
                }
            }
        }
        return instance;
    }

    public String getEnv() {
        return env;
    }

    public static String fillingEnv(String env) {
        if (!effectiveActivePlaceholders.contains(env))
            throw new RuntimeException("env : Illegal parameter!");
        if (env.equals("pro")) {
            return "https://api.up3dlink.com";
        }
        return envTemplate.replace(activePlaceholder, env);
    }
}
